package main

import (
	"fmt"
	"time"
)

var intChan = make(chan int, 200000)

func main() {
	go initChan(200000)
	saveChan := make(chan int, 200000)
	exitChan := make(chan bool, 10)

	for i := 0; i < 10; i++ {
		go isPrime(intChan, saveChan, exitChan)
	}

	// 给主进程加协程，等待isPrime执行完成；防止主进程退出
	// 如果没有关闭管道： fatal error: all goroutines are asleep - deadlock!
	go func() {
		for i := 0; i < 10; i++ {
			<-exitChan
		}
		close(saveChan)
	}()

	for {
		num, ok := <-saveChan
		if !ok {
			break
		}
		fmt.Println(num)
	}

}

// 计算是否是素数
func isPrime(intChan chan int, saveChan chan int, exitChan chan bool) {
	time.Sleep(100 * time.Millisecond)
	for {
		num, ok := <-intChan
		if !ok {
			break
		}
		flag := true
		for i := 2; i <= num/2; i++ {
			if num%i == 0 {
				flag = false
				break
			}
		}
		if flag {
			saveChan <- num
		}
	}
	exitChan <- true
}

// 把数据加入channel中
func initChan(num int) {
	for i := 1; i < num; i++ {
		intChan <- i
	}
	close(intChan)
}
